<script setup lang="ts">
import { reactive, ref, onBeforeMount } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { user as useUser } from '@/store'
import { TabletOutlined, KeyOutlined } from '@ant-design/icons-vue'
import type { loginFormInfoType } from './type'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { verifyPic as _verifyPic } from '@/assets/imgs/verifyPic'
import mockRequest from '@/mock/request'

const router = useRouter()
const route = useRoute()
const userStore = useUser()
const formState: { phone: string; verifyCode: string } = reactive({
	phone: '',
	verifyCode: '',
})

const isLoading = ref(false)
const formRef = ref<FormInstance>()
const time = ref(0)
let timer: any

const phoneReg = /^\d{11}$/

const rules = {
	phone: [
		{ required: true, message: '请输入你的手机号!' },
		{ pattern: phoneReg, message: '请输入正确格式的手机号!' },
	],
	verifyCode: [
		{ required: true, message: '请输入你的验证码!' },
		{ pattern: /^\d{6}$/, message: '请输入6位数字的验证码!' },
	],
}

onBeforeMount(() => {
	const { phone } = userStore.loginInfo
	if (phone) {
		formState.phone = phone
	}
})

const resetF = () => {
	console.log({ ...formRef.value })
	formRef.value?.resetFields()
}

const bindSendVerifyCode = async () => {
	if (!formState.phone) {
		message.warning('请填写手机号！')
		return
	}
	if (!phoneReg.test(formState.phone)) {
		message.warning('请填写正确格式的手机号！')
		return
	}
	const res = await mockRequest(() => ({ code: 200, expire: 10 }), true, '获取验证码中...')
	console.log(res)
	if (res && res.code) {
		time.value = res.expire
		timer = setInterval(() => {
			if (time.value <= 0) {
				clearInterval(timer)
				timer = 0
				return
			}
			time.value--
		}, 1000)
	} else {
		message.warning('获取验证码失败！')
	}
}

const success = async (values: loginFormInfoType) => {
	if (isLoading.value) return
	//console.log(values)
	isLoading.value = true
	const { phone, verifyCode } = formState
	const res = await userStore.loginByPhone({ phone, verifyCode })
	isLoading.value = false

	if (res && res.code == 200) {
		const { id } = userStore.loginInfo
		if (route.query.redirect && res.id === id)
			// 防止重定向到没有权限的页面
			router.push(decodeURIComponent(route.query.redirect as string))
		else router.push('/')
		userStore.$patch((s) => {
			s.loginInfo = { ...s.loginInfo, id: res.id, phone: values.phone, activeTab: 'phone' }
		})
	}
	if (res && res.code == 201) message.warn('手机号错误！')
}

const fail = (err: any) => {
	console.log('err', err)
}
</script>

<template>
	<a-form class="phone-form" ref="formRef" :rules="rules" :model="formState" @finish="success" @finishFailed="fail">
		<a-form-item name="phone">
			<a-input v-model:value="formState.phone" placeholder="请输入手机号" allowClear>
				<template #prefix>
					<TabletOutlined class="site-form-item-icon" />
				</template>
			</a-input>
		</a-form-item>

		<a-form-item name="verifyCode">
			<a-input v-model:value="formState.verifyCode" placeholder="请输入验证码" style="width: 60%; margin-right: 10px" allowClear>
				<template #prefix>
					<KeyOutlined class="site-form-item-icon" />
				</template>
			</a-input>
			<a-button :disabled="!!time" @click="bindSendVerifyCode">获取验证码{{ `${time ? `(${time})` : ''}` }}</a-button>
		</a-form-item>

		<a-form-item>
			<a-button type="primary" html-type="submit" class="phone-form-button" style="margin-top: 10px" :loading="isLoading"> 登录 </a-button>
		</a-form-item>
	</a-form>
</template>

<style lang="less" scoped>
.phone-form {
	.phone-form-button {
		width: 100%;
	}
}
</style>
